package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.PaymentOrder;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.VipPackage;
import com.shlh.saas.service.UserService;
import com.shlh.saas.service.PaymentOrderService;
import com.shlh.saas.service.VipPackageService;
import com.shlh.saas.util.XMLUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PaymentOrderService paymentOrderService;
    
    @Autowired
    private VipPackageService vipPackageService;
    
    /**
     * 创建支付订单（通过用户登录态获取用户ID）
     */
    @PostMapping("/order/create")
    public Result createOrder(@RequestBody Map<String, Object> params) {
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录");
            }
            
            // 获取参数
            Integer paymentType = Integer.parseInt(params.get("paymentType").toString()); // 1-微信，2-支付宝
            String packageType = params.get("packageType").toString(); // VIP、EMAIL、CUSTOM
            
            BigDecimal amount;
            Integer packagePoints = 0;
            String packageDuration = "0";
            
            // 如果是VIP套餐，从套餐表获取信息
            if ("VIP".equals(packageType) && params.containsKey("packageId")) {
                Long packageId = Long.parseLong(params.get("packageId").toString());
                VipPackage vipPackage = vipPackageService.getPackageById(packageId);
                
                if (vipPackage == null) {
                    return Result.error("套餐不存在");
                }
                
                // 使用套餐表中的价格
                amount = vipPackage.getPrice();
                // 存储套餐ID到packagePoints字段
                packagePoints = packageId.intValue();
                // 存储套餐时长
                packageDuration = String.valueOf(vipPackage.getDuration());
                
                log.info("用户{}购买VIP套餐：ID={}, 名称={}, 价格={}", userId, packageId, vipPackage.getName(), amount);
            } else {
                // 自定义金额充值或邮件套餐
                amount = new BigDecimal(params.get("amount").toString());
                
                // 可选参数
                packagePoints = params.containsKey("packagePoints") ? 
                        Integer.parseInt(params.get("packagePoints").toString()) : 0;
                packageDuration = params.containsKey("packageDuration") ? 
                        params.get("packageDuration").toString() : "0";
            }
            
            // 创建订单
            PaymentOrder order = paymentOrderService.createPaymentOrder(
                    userId, amount, paymentType, packageType, packagePoints, packageDuration);
            
            // 返回订单信息
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", order.getOrderNo());
            
            if (paymentType == 1) { // 微信支付
                data.put("codeUrl", order.getQrCodeUrl());
            } else if (paymentType == 2) { // 支付宝支付
                data.put("form", order.getQrCodeUrl());
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("创建支付订单异常", e);
            return Result.error("创建支付订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建支付订单（通过手机号获取用户）
     */
    @PostMapping("/create")
    @Transactional
    public Result createOrderByPhone(@RequestBody Map<String, Object> params) {
        try {
            // 获取参数
            String phone = params.get("phone").toString();
            Integer paymentType = params.containsKey("paymentType") ? 
                    Integer.parseInt(params.get("paymentType").toString()) : 
                    (params.containsKey("type") ? ("alipay".equals(params.get("type")) ? 2 : 1) : 2);
            String packageType = params.containsKey("packageType") ? 
                    params.get("packageType").toString() : "CUSTOM";
            
            // 验证用户是否存在
            User user = userService.findByPhone(phone);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            BigDecimal amount;
            Integer packagePoints = 0;
            String packageDuration = "0";
            
            // 如果是VIP套餐，从套餐表获取信息
            if ("VIP".equals(packageType) && params.containsKey("packageId")) {
                Long packageId = Long.parseLong(params.get("packageId").toString());
                VipPackage vipPackage = vipPackageService.getPackageById(packageId);
                
                if (vipPackage == null) {
                    return Result.error("套餐不存在");
                }
                
                // 使用套餐表中的价格
                amount = vipPackage.getPrice();
                // 存储套餐ID到packagePoints字段
                packagePoints = packageId.intValue();
                // 存储套餐时长
                packageDuration = String.valueOf(vipPackage.getDuration());
                
                log.info("用户{}购买VIP套餐：ID={}, 名称={}, 价格={}", phone, packageId, vipPackage.getName(), amount);
            } else {
                // 自定义金额充值或邮件套餐
                amount = new BigDecimal(params.get("amount").toString());
                
                // 验证金额
                if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                    return Result.error("充值金额必须大于0");
                }
                
                // 可选参数
                packagePoints = params.containsKey("packagePoints") ? 
                        Integer.parseInt(params.get("packagePoints").toString()) : 0;
                packageDuration = params.containsKey("packageDuration") ? 
                        params.get("packageDuration").toString() : "0";
            }
            
            // 创建支付订单
            PaymentOrder order = paymentOrderService.createPaymentOrder(
                user.getId(), 
                amount, 
                paymentType,
                packageType,
                packagePoints,
                packageDuration
            );
            
            // 返回订单信息
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", order.getOrderNo());
            
            if (paymentType == 1) { // 微信支付
                data.put("codeUrl", order.getQrCodeUrl());
            } else if (paymentType == 2) { // 支付宝支付
                data.put("form", order.getQrCodeUrl());
            }
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return Result.error("创建支付订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建支付宝支付订单（兼容旧接口）
     */
    @PostMapping("/alipay/create")
    public Result createAlipayOrder(@RequestBody Map<String, Object> params) {
        // 添加支付类型参数
        params.put("paymentType", 2); // 2-支付宝支付
        return createOrderByPhone(params);
    }
    
    /**
     * 创建微信支付订单（兼容旧接口）
     */
    @PostMapping("/wechat/create")
    public Result createWechatPayOrder(@RequestBody Map<String, Object> params) {
        // 添加支付类型参数
        params.put("paymentType", 1); // 1-微信支付
        return createOrderByPhone(params);
    }
    
    /**
     * 查询订单状态
     */
    @GetMapping("/order/query")
    public Result queryOrderDetail(@RequestParam String orderNo) {
        try {
            PaymentOrder order = paymentOrderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("orderNo", order.getOrderNo());
            data.put("status", order.getStatus());
            data.put("amount", order.getAmount());
            data.put("paymentType", order.getPaymentType());
            data.put("createTime", order.getCreateTime());
            data.put("payTime", order.getPayTime());
            data.put("packageType", order.getPackageType());
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("查询订单状态异常", e);
            return Result.error("查询订单状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询订单状态（兼容旧接口）
     */
    @GetMapping("/query")
    public Result queryOrder(@RequestParam String orderNo, @RequestParam(required = false) String type) {
        return queryOrderDetail(orderNo);
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/order/cancel")
    public Result cancelOrder(@RequestParam String orderNo) {
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return Result.error("未登录");
            }
            
            // 获取订单信息
            PaymentOrder order = paymentOrderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                return Result.error("订单不存在");
            }
            
            // 验证订单所属
            if (!order.getUserId().equals(userId)) {
                return Result.error("无权操作此订单");
            }
            
            // 验证订单状态
            if (order.getStatus() != 0) {
                return Result.error("订单状态不允许取消");
            }
            
            // 更新订单状态为已取消
            order.setStatus(2); // 已取消
            boolean updated = paymentOrderService.updateById(order);
            
            if (updated) {
                return Result.success("订单已取消");
            } else {
                return Result.error("取消订单失败");
            }
        } catch (Exception e) {
            log.error("取消订单异常", e);
            return Result.error("取消订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 支付宝回调接口
     */
    @PostMapping("/alipayNotify")
    public String alipayNotify(HttpServletRequest request) {
        try {
            // 获取所有请求参数
            Map<String, String> params = new HashMap<>();
            request.getParameterMap().forEach((key, values) -> {
                String value = values[0];
                params.put(key, value);
            });
            
            log.info("收到支付宝回调: {}", params);
            
            // 处理回调
            boolean success = paymentOrderService.handleAlipayNotify(params);
            
            // 返回结果
            return success ? "success" : "fail";
        } catch (Exception e) {
            log.error("处理支付宝回调异常", e);
            return "fail";
        }
    }
    
    /**
     * 微信支付回调接口
     */
    @PostMapping("/wechatNotify")
    public String wechatNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取请求体
            StringBuilder sb = new StringBuilder();
            try (java.io.BufferedReader br = request.getReader()) {
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
            }
            
            String notifyData = sb.toString();
            log.info("收到微信支付回调: {}", notifyData);
            
            // 解析XML数据
            Map<String, String> notifyMap;
            try {
                notifyMap = XMLUtil.xmlToMap(notifyData);
            } catch (Exception e) {
                log.error("解析微信支付回调XML数据失败", e);
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[XML解析失败]]></return_msg></xml>";
            }
            
            // 处理回调
            boolean success = paymentOrderService.handleWechatPayNotify(notifyMap);
            
            // 设置响应头
            response.setContentType("text/xml");
            
            // 返回结果
            if (success) {
                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            } else {
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>";
            }
        } catch (Exception e) {
            log.error("处理微信支付回调异常", e);
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理异常]]></return_msg></xml>";
        }
    }
} 